package com.exception;

import com.broker.base.protocol.response.Resp;
import com.commom.AppRespError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class HttpGlobalExceptionAdvice {

    private String getValidatedFailedMsg(List<ObjectError> errors){
        List<String> msgs = errors.stream()
                .map(v->{
                    if(v instanceof FieldError){
                        return "属性:"+((FieldError)v).getField() + " " + v.getDefaultMessage();
                    }
                    return v.getDefaultMessage();
                })
                .collect(Collectors.toList());

        return String.join("; ", msgs);
    }
    /**
     * 一般的参数绑定时候抛出的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Resp<String>  handleBindException(BindException ex){
        log.error("参数校验异常",ex);
        String errorStart = "参数校验错误:";
        return Resp.failed(errorStart + getValidatedFailedMsg(ex.getBindingResult().getAllErrors()), AppRespError.REQUEST_VERIFY_ERROR.getCode());
    }


    /**
     * 一般的参数绑定时候抛出的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Resp<String>  handleBindException(MethodArgumentNotValidException ex){
        log.error("参数校验异常",ex);
        String errorStart = "参数校验错误:";
        return Resp.failed(errorStart + getValidatedFailedMsg(ex.getBindingResult().getAllErrors()), AppRespError.REQUEST_VERIFY_ERROR.getCode());
    }



    /**
     * 拦截所有运行时的全局异常   
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Resp<String> runtimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return Resp.failed(AppRespError.SERVICE_ERROR);
    }

    /**
     * 拦截所有运行时的服务异常   
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Resp<String> serviceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return Resp.failed(e.getRespErrorCode());
    }

    /**
     * 系统异常捕获处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Resp<String>  exception(Exception e) {
        log.error(e.getMessage(), e);
        return Resp.failed(AppRespError.SERVICE_ERROR);
    }

}
